﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Configuration;
using Microsoft.Win32;
using System.IO;
using System.Xml;

namespace WindowsManager
{
    public partial class Opertaion : Form
    {
        public Opertaion()
        {
            InitializeComponent();
        }
        string ServiceNames = null;
        int time = 5;
        List<string> AllServices = new List<string>();
        private void Opertaion_Load(object sender, EventArgs e)
        {
            try
            {
                ServiceNames = ConfigurationManager.AppSettings["ServiceName"];
                string times = ConfigurationManager.AppSettings["time"];
                time = Convert.ToInt32(times);
                //开机是否自动启动
                //获得文件的当前路径   
                string dir = Directory.GetCurrentDirectory();
                //获取可执行文件的全部路径   
                string exeDir = dir + "\\WindowsManager.exe";

                //获取Run键   
                RegistryKey key11 = Registry.LocalMachine;
                RegistryKey key12 = key11.CreateSubKey("SOFTWARE");
                RegistryKey key13 = key12.CreateSubKey("Microsoft");
                RegistryKey key14 = key13.CreateSubKey("Windows");
                RegistryKey key15 = key14.CreateSubKey("CurrentVersion");
                RegistryKey key16 = key15.CreateSubKey("Run");
                //在Run键中写入一个新的键值   
                if (key16.GetValue("WindowsManager") == null)
                {
                    this.checkBox1.Checked = false;
                }
                else if (key16.GetValue("WindowsManager").ToString().Trim() != exeDir.Trim())
                {
                    this.checkBox1.Checked = false;
                }
                else
                {
                    this.checkBox1.Checked = true;
                }
            }
            catch
            {
                MessageBox.Show("配置文件异常，请正确修改配置文件！");
                Application.Exit();
            }

            //this.domainUpDown1
            comm();
            this.textBox1.Text = time.ToString();
        }
        private void comm()
        {
            ServiceController[] services = System.ServiceProcess.ServiceController.GetServices();
            AllServices = new List<string>();
            for (int i = 0; i < services.Length; i++)
            {
                //System.Console.WriteLine(string.Format("{0} {1} {2}", services[i].ServiceName, services[i].DisplayName, services[i].Status.ToString()));
                AllServices.Add(services[i].ServiceName);
                // Console.WriteLine(services[i].ServiceType);
            }
            this.comboBox1.DataSource = AllServices;


            int Toindex = 0;


            for (int i = 0; i < comboBox1.Items.Count; i++)
            {
                if (ServiceNames == comboBox1.Items[i].ToString())
                {
                    Toindex = i;
                }
            }
            this.comboBox1.SelectedIndex = Toindex;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            bool ToUpdate = false;
            for (int i = 0; i < comboBox1.Items.Count; i++)
            {
                if (comboBox1.SelectedItem.ToString() == AllServices[i].ToString() && comboBox1.SelectedItem.ToString() != ServiceNames)
                {
                    //Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    //config.AppSettings.Settings.Remove("ServiceName");
                    //config.AppSettings.Settings.Add("ServiceName", comboBox1.SelectedItem.ToString());
                    //config.Save(ConfigurationSaveMode.Modified);
                    //ConfigurationManager.RefreshSection("appSettings");

                    //ConfigurationManager.AppSettings.Set("ServiceName", comboBox1.SelectedItem.ToString());

                    SetValue("ServiceName", comboBox1.SelectedItem.ToString());
                    ToUpdate = true;
                }
                else if (comboBox1.SelectedItem.ToString() == ServiceNames)
                {
                    ToUpdate = true;
                }
            }
            if(textBox1.Text!=this.time.ToString()){
                SetValue("time", textBox1.Text.Trim());
            }
            if (!ToUpdate)
            {
                MessageBox.Show("保存失败！服务不存在！");
            }
            else
            {
                //if (this.checkBox1.Checked == true)
                //{
                //    RunTorunOS();
                //}
                //else
                //{
                //    StopTorunOS();
                //}
                this.Close();
            }
        }
        public void SetValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            //此处配置文件在程序目录下
            xDoc.Load(Application.StartupPath + "\\WindowsManager.exe.config");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");
            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            if (xElem1 != null)
            {
                xElem1.SetAttribute("value", AppValue);
            }
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);
                xElem2.SetAttribute("value", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(Application.StartupPath + "\\WindowsManager.exe.config");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 设置开机自动运行
        /// </summary>
        private void RunTorunOS()
        {
            try
            {
                //获得文件的当前路径   
                string dir = Directory.GetCurrentDirectory();
                //获取可执行文件的全部路径   
                string exeDir = dir + "\\WindowsManager.exe";
                //获取Run键   
                RegistryKey key11 = Registry.LocalMachine;
                RegistryKey key12 = key11.CreateSubKey("SOFTWARE");
                RegistryKey key13 = key12.CreateSubKey("Microsoft");
                RegistryKey key14 = key13.CreateSubKey("Windows");
                RegistryKey key15 = key14.CreateSubKey("CurrentVersion");
                RegistryKey key16 = key15.CreateSubKey("Run");
                //在Run键中写入一个新的键值   

                if (key16.GetValue("WindowsManager") == null)
                {
                    //this.checkBox1.Checked = false;
                    key16.SetValue("WindowsManager", exeDir);
                }
                else if (key16.GetValue("WindowsManager").ToString().Trim() != exeDir.Trim())
                {
                    key16.SetValue("WindowsManager", exeDir);
                }
                else
                {
                    //
                }
            }
            catch
            {
                MessageBox.Show("开机启动设置失败！被保护程序阻止或者您不是该计算机管理员。");
            }
        }
        /// <summary>
        /// 停止开机自动运行
        /// </summary>
        private void StopTorunOS()
        {
            try
            {
                //获得文件的当前路径   
                string dir = Directory.GetCurrentDirectory();
                //获取可执行文件的全部路径   
                string exeDir = dir + "\\WindowsManager.exe";
                //获取Run键   
                RegistryKey key11 = Registry.LocalMachine;
                RegistryKey key12 = key11.CreateSubKey("SOFTWARE");
                RegistryKey key13 = key12.CreateSubKey("Microsoft");
                RegistryKey key14 = key13.CreateSubKey("Windows");
                RegistryKey key15 = key14.CreateSubKey("CurrentVersion");
                RegistryKey key16 = key15.CreateSubKey("Run");
                //判断是否存在  
                if (key16.GetValue("WindowsManager") == null)
                {
                    //this.checkBox1.Checked = false;
                }
                else
                {
                    key16.DeleteValue("WindowsManager");
                }
            }
            catch
            {
                MessageBox.Show("设置失败！被保护程序阻止或者您不是该计算机管理员。");
            }
        }
    }
}
